package hn.cch.advanced.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ImplementsCallable implements Callable<String> {

    @Override
    public String call() throws Exception {

        System.out.println("StringCallable");
        return "StringCallable";
    }


    public static void main(String[] args) {

        execute();
        // submit();

    }

    /**
     * 线程池的execute方法参数实现Runnable接口，没有返回值
     */
    public static void execute() {
        // Executors类的静态方法
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        // ExecutorService executorService = Executors.newFixedThreadPool(2);
        // ExecutorService executorService = Executors.newCachedThreadPool();
        // ExecutorService executorService = Executors.newScheduledThreadPool(2);
        // 新增的
        // ExecutorService executorService = Executors.newWorkStealingPool();

        ImplementsRunnable implementsRunnable = new ImplementsRunnable();

        executorService.execute(implementsRunnable);

        executorService.shutdown();

    }

    /**
     * 线程池的submit方法参数实现Callable接口，有返回值
     */
    public static void submit() {

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2, 1000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(2));

        ImplementsCallable implementsCallable = new ImplementsCallable();

        Future<String> stringFuture = threadPoolExecutor.submit(implementsCallable);

        // 查看任务是否执行完成
        while (!stringFuture.isDone()) {
            try {
                System.out.println("future sleep");
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        try {
            // 获取任务返回结果
            System.out.println(stringFuture.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        threadPoolExecutor.shutdown();
    }

}